import { login, reqGetUser, reqAvatar } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
// import { reject, resolve } from 'core-js/fn/promise'
import { Message } from 'element-ui'

const state = {

  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, content) {
    state.userInfo = content
  },
  rushToken(state) {
    state.token = ''

    removeToken()
  },
  rushUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  rushBoth(context) {
    context.commit('rushToken')
    context.commit('rushUserInfo')
  },
  // async getToken(context, form) {
  //   // console.log(123)
  //   const { data } = await login(form)
  //   console.log(data, '999')
  //   context.commit('setToken', data.data)
  //   console.log(data.data)
  // }
  getToken(context, data) {
    return new Promise((resolve, reject) => {
      login(data).then((res) => {
        console.log(res)
        context.commit('setToken', res.data)

        resolve(res)
      }).catch((error) => {
        Message.error(error.essage)
        //  console.log(error);
        reject(error)
      })
    })
  },
  async getUserInfo(context) {
    const { data: data1 } = await reqGetUser()
    const { data: data2 } = await reqAvatar(data1.userId)
    console.log(data1, '获取用户信息')
    console.log(data2, '获取用户信息')
    const obj = {
      ...data1,
      ...data2
    }
    context.commit('setUserInfo', obj)
    return obj
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
